import { useQuasar, QVueGlobals } from 'quasar';
export const STORE_NAME = 'VideoEditorStore';
export default class VideoEditorDBHelper {
  db: IDBDatabase | null = null;
  $q: QVueGlobals | null = null;
  constructor() {
    this.$q = useQuasar();
  }
  initDB(): Promise<IDBDatabase> {
    return new Promise((resolve, reject) => {
      const request = window.indexedDB.open(STORE_NAME, 1);
      request.onerror = (error) => {
        this.$q?.dialog({
          title: 'Error',
          message: 'Your Broswer may not surpport video editting',
        });
        reject(error);
      };
      request.onsuccess = () => {
        this.db = request.result;
        resolve(this.db);
      };
      request.onupgradeneeded = (e: any) => {
        const dbInstance: IDBDatabase = e?.target.result as IDBDatabase;
        const objectStore = dbInstance.createObjectStore(STORE_NAME, {
          keyPath: 'id',
        });
        objectStore.createIndex('id', 'id', { unique: true });
      };
    });
  }
  get(id: string): Promise<any> {
    return new Promise((resolve, reject) => {
      const store = this.db?.transaction(STORE_NAME).objectStore(STORE_NAME);
      if (store) {
        const req = store.get(id);
        req.onsuccess = () => {
          if (req.result) {
            resolve(req.result);
          } else {
            resolve(null);
          }
        };
        req.onerror = (error) => {
          reject(error);
        };
      } else {
        reject(new Error('Database Not Found Error'));
      }
    });
  }
  store(id: string, video: any, audio: any): Promise<void> {
    return new Promise((resolve, reject) => {
      const store = this.db
        ?.transaction(STORE_NAME, 'readwrite')
        .objectStore(STORE_NAME);
      const record = {
        id: id,
        video: video,
        audio: audio,
      };
      const req = store!.add(record);
      req.onsuccess = () => {
        resolve();
      };
      req.onerror = (error) => {
        reject(error);
      };
    });
  }
  remove(id: string): Promise<void> {
    return new Promise((resovle, reject) => {
      const store = this.db
        ?.transaction(STORE_NAME, 'readwrite')
        .objectStore(STORE_NAME);
      const req = store!.delete(id);
      req.onsuccess = () => {
        resovle();
      };
      req.onerror = (error) => {
        reject(error);
      };
    });
  }
}
